$watch ( type in module ng )

Description

Registers a listener callback to be executed whenever the watchExpression changes.

If you want to be notified whenever $digest is called, you can register a watchExpression function with no listener . (Since watchExpression can execute multiple times per $digest cycle when a change is detected, be prepared for multiple calls to your listener.)

After a watcher is registered with the scope, the listener fn is called asynchronously (via $evalAsync) to initialize the watcher. In rare cases, this is undesirable because the listener is called when the result of watchExpression didn't change. To detect this scenario within the listener fn, you can compare the newVal and oldVal . If these two values are identical ( === ) then the listener was called due to initialization.

Example

           // let's assume that scope was dependency injected as the $rootScope
           var scope = $rootScope;
           scope.name = 'misko';
           scope.counter = 0;

           expect(scope.counter).toEqual(0);
           scope.$watch('name', function(newValue, oldValue) { scope.counter = scope.counter + 1; });
           expect(scope.counter).toEqual(0);

           scope.$digest();
           // no variable change
           expect(scope.counter).toEqual(0);

           scope.name = 'adam';
           scope.$digest();
           expect(scope.counter).toEqual(1);

Usage

Scope#$watch(watchExpression[, listener][, objectEquality]);

Parameters

Returns

{function()}

Returns a deregistration function for this listener.